package com.liuzy.servlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.liuzy.openapi.BaiduApi;
import com.liuzy.util.Util;

/**
 * @author liuzy
 * @since 2015年10月26日
 */
public class ShortUrlServlet extends HttpServlet {

	private static final long serialVersionUID = 6868688452600749453L;

	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		Util.log("req->", request.getServletPath() + Util.getAllParams2kv(request));
		try {
			String url = request.getParameter("url");
			if (url == null || url.isEmpty())
				return;
			String callback = request.getParameter("callback");
			String result = BaiduApi.shortUrl(url);
			if (callback != null && !callback.isEmpty()) {
				result = callback + "('" + result + "');";
			}
			Util.log("res->", result );
			response.setContentType("text/plain; charset=utf-8");
			response.getWriter().write(result);
			response.getWriter().flush();
			response.getWriter().close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		doGet(req, resp);
	}

}
